package com.sinoglobal.ningxia.activity.vip;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.orhanobut.logger.Logger;
import com.sinoglobal.dumping.DumplingInterface;
import com.sinoglobal.dumping.base.Dumpling_SinoConstans;
import com.sinoglobal.networkconnections.HttpTools;
import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.activity.base.BaseActivity;
import com.sinoglobal.ningxia.beans.LoginVo;
import com.sinoglobal.ningxia.beans.UserJurisdictionBean;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.ningxia.http.Code;
import com.sinoglobal.ningxia.http.ConnectionUtil;
import com.sinoglobal.ningxia.utils.ItktLog;
import com.sinoglobal.ningxia.utils.MContants;
import com.sinoglobal.ningxia.utils.SharedPreferenceUtil;
import com.sinoglobal.ningxia.utils.TextUtil;
import com.sinoglobal.ningxia.utils.UserUtils;
import com.sinoglobal.ningxia.utils.ValidUtil;
import com.sinoglobal.ningxia.widget.PwdSlipButton;
import com.sinoglobal.ningxia.widget.PwdSlipButton.OnChangedListener;
import com.sinoglobal.shakeprize.utils.Contstent;
import com.sinoglobal.shakeprize.utils.SPUtil;
import com.sinoglobal.sinostore.SinoStore;
import com.sinoglobal.wallet.app.SinoValueManager;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zhy.http.okhttp.request.RequestCall;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.HashMap;

import okhttp3.Call;

/**
 * @author lms
 * @title: LoginActivity.java
 * @package com.sinoglobal.ningxia.activity.vip
 * @description: 登录页面
 * @date 2014-6-17 下午5:10:28
 */
public class Login extends BaseActivity implements OnClickListener, OnFocusChangeListener {
    // 手机号码输入框，密码输入框
    private EditText phoneEdit, pwdEdit;
    // 找回密码，登录，注册
    private TextView findPwd, login, regist;
    // 自动登录
    private CheckBox autoLogin;
    // 滑动开关
    private PwdSlipButton slipButton;
    // 意图传递
    private Intent intent;
    // 手机号码字符串
    private String phoneStr;
    // 密码字符串
    private String pwdStr;
    // 记录自动登录是否选中
    private boolean isAutoChecked = false;
    // 是否显示明文密码
    private boolean checkChanged = false;
    // 跳转的activity名称
    private String activityName;
    private ProgressDialog pbLogin;
    private RequestCall requestCall;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vip_login);
        openChenJInShi();//开启沉浸式
        init();
        autoLogin();
        setOnClickListener();
        setOnFocusChangeListener();
    }

    // 自动登录
    private void autoLogin() {
        // 判断是否自动登录
        isAutoChecked = SharedPreferenceUtil.getBoolean(FlyApplication.context, "autoLogin");
        String autoUserName = SharedPreferenceUtil.getString(FlyApplication.context, "autoName");
        String autoPwd = SharedPreferenceUtil.getString(FlyApplication.context, "autoPwd");
        if (isAutoChecked) {
            autoLogin.setChecked(isAutoChecked);// 选中自动登录
            phoneEdit.setText(autoUserName);
            pwdEdit.setText(autoPwd);
            pwdEdit.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            // 将光标移至末尾
            pwdEdit.setSelection(autoPwd.length());

            phoneStr = phoneEdit.getText().toString().trim();// 手机号码字符串
            pwdStr = pwdEdit.getText().toString().trim();// 密码字符串
        }
    }

    // 添加按钮的监听事件
    private void setOnClickListener() {
        findPwd.setOnClickListener(this);
        regist.setOnClickListener(this);
        login.setOnClickListener(this);

        slipButton.SetOnChangedListener(new OnChangedListener() {

            @Override
            public void OnChanged(boolean CheckState) {
                ItktLog.i("----------->" + CheckState);
                pwdStr = pwdEdit.getText().toString().trim();
                checkChanged = CheckState;
                // 当滑动按钮状态改变时，改变密码输入的样式
                if (checkChanged) {
                    // 圆点密码样式
                    pwdEdit.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    // 将光标移至末尾
                    pwdEdit.setSelection(pwdStr.length());
                } else {
                    // 显示文本样式
                    pwdEdit.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
                    pwdEdit.setSelection(pwdStr.length());
                }
            }
        });
    }

    // 添加 改变焦点事件监听
    private void setOnFocusChangeListener() {
        phoneEdit.setOnFocusChangeListener(this);
        pwdEdit.setOnFocusChangeListener(this);
    }

    // 初始化view
    private void init() {
        titleView.setText(R.string.login);
        activityName = getIntent().getStringExtra("activity");
        findPwd = (TextView) findViewById(R.id.tv_find_pwd);
        login = (TextView) findViewById(R.id.tv_login);
        regist = (TextView) findViewById(R.id.tv_regist);
        autoLogin = (CheckBox) findViewById(R.id.ck_auto_login);
        slipButton = (PwdSlipButton) findViewById(R.id.pwd_slip_btn);
        slipButton.setCheck(false);
        phoneEdit = (EditText) findViewById(R.id.edit_phone);
        // 手机号不为空时（已经登录过），自动填写手机号码
        try {
            String phoneString = SharedPreferenceUtil.getString(FlyApplication.context, "username");
            phoneEdit.setText(phoneString);
        } catch (Exception e) {
            e.printStackTrace();
        }
        pwdEdit = (EditText) findViewById(R.id.edit_pwd);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.sinoglobal.hljtv.finish");
    }

    @Override
    public void onClick(View v) {
        if (!isNetworkConnected(FlyApplication.context)) {
            showShortToastMessage(getResources().getString(R.string.no_connections));
            return;
        }
        switch (v.getId()) {
            case R.id.tv_find_pwd:// 点击找回密码
                intent = new Intent(Login.this, PasswordFind.class);
                this.startActivity(intent);
                pushActivity(Login.this);
                break;
            case R.id.tv_login:// 点击登录
                phoneStr = phoneEdit.getText().toString().trim();// 手机号码字符串
                pwdStr = pwdEdit.getText().toString().trim();// 密码字符串
                login(phoneStr, pwdStr, activityName);
                break;
            case R.id.tv_regist:// 点击注册
                intent = new Intent(Login.this, Regist.class);
                intent.putExtra("activityName", activityName);
                this.startActivity(intent);
                pushActivity(Login.this);// 将登录activity压栈
                break;
        }
    }

    // 验证输入的登录信息
    public void login(final String phoneStr, final String pwdStr, final String activityName) {
        validPhone();
        validPwd();
        String message = "正在登录中...";
        HashMap<String, String> params = new HashMap<>();
        params.put("por", "1000");
        params.put("username", phoneStr);
        params.put("pwd", pwdStr);


        pbLogin = ProgressDialog.show(Login.this, null, message, true, true);
        requestCall = HttpTools.getInstance().post(Login.this, ConnectionUtil.URL, params);
        requestCall.execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (pbLogin != null) {
                    pbLogin.dismiss();
                }
                showShortToastMessage(getResources().getString(R.string.login_fail));
            }

            @Override
            public void onResponse(String response, int id) {
                LoginVo result = JSON.parseObject(response, LoginVo.class);

                if (pbLogin != null) {
                    pbLogin.dismiss();
                    // 数据为空
                    if (null == result) {
                        if (pbLogin != null) {
                            pbLogin.dismiss();
                        }
                        showShortToastMessage(getResources().getString(R.string.login_fail));
                        return;
                    }

                    if (Code.CODE_SUCCESS != result.getCode()) {
                        showShortToastMessage(result.getMessage());
                        return;
                    }
                    new Thread() {
                        public void run() {
                            HttpGet httpRequest = new HttpGet(ConnectionUtil.PORTAL_VAILED + phoneStr);
                            try {
                                // 发送请求并等待响应
                                HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);

                                if (httpResponse.getStatusLine().getStatusCode() == 200) {
                                    String strResult;
                                    strResult = EntityUtils.toString(httpResponse.getEntity());
                                    UserJurisdictionBean userJurisdictionBean = JSON.parseObject(strResult, UserJurisdictionBean.class);
                                    EventBus.getDefault().post(userJurisdictionBean);
                                    JSONObject jb = new JSONObject(strResult);
                                    // 1代表验证通过可以显示会议入口
                                    if (jb.getString("code").equals("1")) {
                                        SharedPreferenceUtil.saveBoolean(mActivity, SharedPreferenceUtil.IS_PORTAL_FLAG, true);
                                    } else {
                                        SharedPreferenceUtil.saveBoolean(mActivity, SharedPreferenceUtil.IS_PORTAL_FLAG, false);
                                    }
                                    //live 为1 标志这个人可直播
                                    if (jb.getString("live").equals("1")) {
                                        SharedPreferenceUtil.saveBoolean(mActivity, SharedPreferenceUtil.IS_LIVE_FLAG, true);
                                        //保存推流地址 2017年5月9日09:27:46
                                        SharedPreferenceUtil.saveString(mActivity,SharedPreferenceUtil.LIVE_LOCATION,jb.getString("rtmp"));
                                    } else {
                                        SharedPreferenceUtil.saveBoolean(mActivity, SharedPreferenceUtil.IS_LIVE_FLAG, false);
                                    }

                                }


                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    }.start();
                    ItktLog.i("--->" + result.toString());
                    Logger.i("登陆成功后的返回值:" + result.toString());

                    // 判断是否勾选自动登录，勾选则记录密码，否则不记录
                    if (autoLogin.isChecked()) {
                        SharedPreferenceUtil.saveBoolean(FlyApplication.context, "autoLogin", true);
                        SharedPreferenceUtil.saveString(FlyApplication.context, "autoName", phoneStr);
                        SharedPreferenceUtil.saveString(FlyApplication.context, "autoPwd", pwdStr);
                    } else {
                        SharedPreferenceUtil.saveBoolean(FlyApplication.context, "autoLogin", false);
                        SharedPreferenceUtil.saveString(FlyApplication.context, "autoName", phoneStr);
                    }

                    FlyApplication.userId = result.getId();
                    SPUtil.saveString(mActivity, Contstent.USER_ID, result.getUserCenterId());
                    setShareData(result);
                    setDumplingData(result);
                    //保存用户的账号
                    String usernameL = result.getUsername();
                    if (usernameL != null) {
                        SharedPreferenceUtil.saveString(mActivity, SharedPreferenceUtil.USER_NAME, usernameL);
                    } else {
                        SharedPreferenceUtil.saveString(mActivity, SharedPreferenceUtil.USER_NAME, "");
                    }

                    // 判断是否从个人设置页面或者忘记密码页面或者注册页面跳转过来，是则跳转到个人设置页面
                    if ("setPerson".equals(activityName) || "resetPwd".equals(activityName)) {
                        Intent intent = new Intent(Login.this, PersonalInfoSet.class);
                        intent.putExtra("nickname", result.getNickname());
                        startActivity(intent);
                    }

                    // 消息推送使用
                    Intent intent = getIntent();
                    intent.putExtra("login", 1);
                    setResult(0, intent);
                    finish();
                }
            }
        });
//        new ItktAsyncTaskWithDialog<Void, Void, LoginVo>(message, true, true) {
//
//            @Override
//            public LoginVo before(Void... params) throws Exception {
//                return RemoteImpl.getInstance().login(phoneStr, pwdStr);
//            }
//
//            @Override
//            public void after(LoginVo result) {
//                // 数据为空
//                if (null == result) {
//                    dismissWaitingDialog();
//                    showShortToastMessage(getResources().getString(R.string.login_fail));
//                    return;
//                }
//
//                if (Code.CODE_SUCCESS != result.getCode()) {
//                    showShortToastMessage(result.getMessage());
//                    return;
//                }
//                new Thread() {
//                    public void run() {
//                        HttpGet httpRequest = new HttpGet(ConnectionUtil.PORTAL_VAILED + phoneStr);
//                        try {
//                            // 发送请求并等待响应
//                            HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
//
//                            if (httpResponse.getStatusLine().getStatusCode() == 200) {
//                                String strResult;
//                                strResult = EntityUtils.toString(httpResponse.getEntity());
//                                JSONObject jb = new JSONObject(strResult);
//                                // 1代表验证通过可以显示会议入口
//                                if (jb.getString("code").equals("1")) {
//                                    SharedPreferenceUtil.saveBoolean(mActivity, SharedPreferenceUtil.IS_PORTAL_FLAG, true);
//                                    //live 为1 标志这个人可直播
//                                    if (jb.getString("live").equals("1")) {
//                                        SharedPreferenceUtil.saveBoolean(mActivity, SharedPreferenceUtil.IS_LIVE_FLAG, true);
//                                    } else {
//                                        SharedPreferenceUtil.saveBoolean(mActivity, SharedPreferenceUtil.IS_LIVE_FLAG, false);
//                                    }
//                                } else {
//                                    SharedPreferenceUtil.saveBoolean(mActivity, SharedPreferenceUtil.IS_PORTAL_FLAG, false);
//                                }
//                            }
//
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }.start();
//                ItktLog.i("--->" + result.toString());
//                Logger.i("登陆成功后的返回值:" + result.toString());
//                // 判断是否勾选自动登录，勾选则记录密码，否则不记录
//                if (autoLogin.isChecked()) {
//                    SharedPreferenceUtil.saveBoolean(FlyApplication.context, "autoLogin", true);
//                    SharedPreferenceUtil.saveString(FlyApplication.context, "autoName", phoneStr);
//                    SharedPreferenceUtil.saveString(FlyApplication.context, "autoPwd", pwdStr);
//                } else {
//                    SharedPreferenceUtil.saveBoolean(FlyApplication.context, "autoLogin", false);
//                    SharedPreferenceUtil.saveString(FlyApplication.context, "autoPwd", pwdStr);
//                }
//
//                FlyApplication.userId = result.getId();
//                SPUtil.saveString(mActivity, Contstent.USER_ID, result.getUserCenterId());
//                setShareData(result);
//                setDumplingData(result);
//                //保存用户的账号
//                String usernameL = result.getUsername();
//                if (usernameL != null) {
//                    SharedPreferenceUtil.saveString(mActivity, SharedPreferenceUtil.USER_NAME, usernameL);
//                } else {
//                    SharedPreferenceUtil.saveString(mActivity, SharedPreferenceUtil.USER_NAME, "");
//                }
//
//
//                // 判断是否从个人设置页面或者忘记密码页面或者注册页面跳转过来，是则跳转到个人设置页面
//                if ("setPerson".equals(activityName) || "resetPwd".equals(activityName)) {
//                    Intent intent = new Intent(Login.this, PersonalInfoSet.class);
//                    intent.putExtra("nickname", result.getNickname());
//                    startActivity(intent);
//                }
//
//                // 消息推送使用
//                Intent intent = getIntent();
//                intent.putExtra("login", 1);
//                setResult(0, intent);
//                finish();
//
//            }
//
//            @Override
//            public void exception() {
//                dismissWaitingDialog();
//                showShortToastMessage(getResources().getString(R.string.login_fail));
//            }
//        }.execute();
    }

    // 设置share存储登录信息
    private void setShareData(LoginVo result) {
        // 初始化商城
        SinoStore.initData(result.getId(), result.getUserCenterId(), result.getUsername(), result.getNickname(), result.getScore());
        Logger.i("登录成功保存ID" + result.getId());
        UserUtils.LoginSuccess(result);
        Intent jifen = new Intent(MContants.BROADCAST_JIFEN);
        sendBroadcast(jifen);
    }

    private void setDumplingData(LoginVo result) {
        DumplingInterface.login(Login.this, result.getUsername(), result.getUserCenterId());
        //init wallet  id 产品标识  电话
        SinoValueManager.getInstance().setIdProductPhone(Login.this, result.getId(), Dumpling_SinoConstans.PRODUCT_CODE, result.getUsername());

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
            case R.id.edit_phone:
                // 失去焦点时对输入的手机号进行校验
                if (!hasFocus) {
                    validPhone();
                }
                break;
            case R.id.edit_pwd:
                // 失去焦点时对输入的密码进行校验
                if (!hasFocus) {
                    validPwd();
                }
                break;
        }
    }

    // 验证输入的手机号码
    private void validPhone() {
        // 手机号码字符串
        phoneStr = phoneEdit.getText().toString().trim();
        // 校验手机号的结果字符串
        String validPhone = ValidUtil.validPhone(phoneStr);
        if (!TextUtil.stringIsNull(validPhone)) {
            showShortToastMessage(validPhone);
            return;
        }
    }

    // 验证输入的密码
    private void validPwd() {
        // 密码字符串
        pwdStr = pwdEdit.getText().toString().trim();
        // 校验密码的结果字符串
        String validPassword = ValidUtil.validPassword(pwdStr);
        if (!TextUtil.stringIsNull(validPassword)) {
            showShortToastMessage(validPassword);
            return;
        }
    }

    // 判断是否连接网络
    public boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        if (requestCall != null) {
            HttpTools.getInstance().httpCancel(requestCall);
        }
        super.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }
}